package com.github.wxiaoqi.security.crm.core.biz;


import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.crm.request.ModifyCustomerMobileParam;
import com.github.wxiaoqi.security.common.crm.request.SavePersonalBaseInfoParam;
import com.github.wxiaoqi.security.common.crm.request.VerifiedRealNameParam;
import com.github.wxiaoqi.security.common.msg.AccountType;
import com.github.wxiaoqi.security.common.msg.LoginRole;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.crm.core.entity.Customer;
import com.github.wxiaoqi.security.crm.core.entity.CustomerMessage;
import com.github.wxiaoqi.security.crm.core.entity.CustomerMessageRel;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccount;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccountJournalInfo;
import com.github.wxiaoqi.security.crm.core.entity.MerchantBase;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccount;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccountJournalInfo;
import com.github.wxiaoqi.security.crm.core.entity.PersonalBase;
import com.github.wxiaoqi.security.crm.core.entity.PersonalBindCard;
import com.github.wxiaoqi.security.crm.core.mapper.CustomerMapper;
import com.github.wxiaoqi.security.crm.core.mapper.CustomerMessageRelMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantBaseMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MessageInfoMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalBaseMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalBindCardMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 注册客户（会员）信息表
 *
 * @author centerroot
 * @email lfw6699@163.com
 * @date 2018-05-25 15:20:48
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class CustomerBiz extends BaseBiz<CustomerMapper,Customer> {
		@Autowired
		private CustomerMapper customerMapper;
		@Autowired
		private PersonalBaseMapper personalBaseMapper;
		@Autowired
		private PersonalBindCardMapper bindCardMapper;
		@Autowired
		private MerchantBaseMapper merchantBaseMapper;
		@Autowired
		private MessageInfoMapper messageInfoMapper;
		@Autowired
		private CustomerMessageRelMapper customerMessageRelMapper;
		@Autowired
		private PersonalAccountJournalMapper personalAccountJournalMapper;
		@Autowired
		private MerchantAccountJournalMapper merchantAccountJournalMapper;
		@Autowired
		private PersonalBaseBiz personalBaseBiz;
		@Autowired
		private MerchantBaseBiz merchantBaseBiz;
		@Autowired
		private PersonalAccountBiz personalAccountBiz;
		@Autowired
		private MerchantAccountBiz merchantAccountBiz;
		@Autowired
		private SmsGateWayBiz smsGateWayBiz;
		@Value("${bountyHunter.acceptBizNo}")
		private String acceptBizNo;
		@Autowired
		private RedisTemplate redisTemplate;
		@Autowired
		private PersonalBindCardMapper personalBindCardMapper;
		/**
		 * 获取用户统计数据
		 * @author centerroot
		 * @time 创建时间:2018年5月23日上午11:31:05
		 * @param param
		 * @return
		 */
		public Map<String, Object> getCustomerStatistics(String customerId){
			log.info("获取用户统计数据   请求参数：{}",customerId);
			Map<String, Object> respMap = new HashMap<String, Object>();
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				if (null != customer.getPerId()) {
					Map<String, Object> reqCustMap = new HashMap<String, Object>();
					reqCustMap.put("perId", customer.getPerId());
					Map<String, Object> respCustMap = personalBaseBiz.getCustStatistics(reqCustMap);
					if (ResponseCode.OK.getCode().equals(respCustMap.get("code"))) {
						respCustMap.remove("code");
						respCustMap.remove("msg");
						respMap.put("custStatistics", respCustMap);
					} else {
						respMap.put("custStatistics", "");
					}
				}else{
					respMap.put("custStatistics", "");
				}
				if (null != customer.getMerId()) {
					Map<String, Object> reqMerMap = new HashMap<String, Object>();
					reqMerMap.put("merId", customer.getMerId());
					Map<String, Object> respMerMap = merchantBaseBiz.getMerStatistics(reqMerMap);
					if (ResponseCode.OK.getCode().equals(respMerMap.get("code"))) {
						respMerMap.remove("code");
						respMerMap.remove("msg");
						respMap.put("merStatistics", respMerMap);
					} else {
						respMap.put("merStatistics", "");
					}
				}else{
					respMap.put("merStatistics", "");
				}
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("获取用户统计数据   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 用户基本信息录入
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午1:43:32
		 * @param param
		 * @return
		 */
		public Map<String, Object> savePersonalBaseInfo(SavePersonalBaseInfoParam baseInfoParam){
			log.info("用户基本信息录入   请求参数：{}",EntityUtils.beanToMap(baseInfoParam));
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = baseInfoParam.getCustomerId();
			// 信息类型 00：会员信息  01： 商户信息
			String infoType = baseInfoParam.getInfoType();
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				if ("00".equals(infoType)) {
					baseInfoParam.setPerId(customer.getPerId());
					respMap = personalBaseBiz.saveCustBaseInfo(baseInfoParam);
				} else {
					if (null != customer.getMerId()) {
						// TODO 商户信息保存
						
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					}else{
						respMap.put("code", ResponseCode.MER_NOTEXIST.getCode());
						respMap.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
					}
				}
				
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("用户基本信息录入   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 用户实名认证信息录入
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午2:46:27
		 * @param param
		 * @return
		 */
		public Map<String, Object> verifiedRealName(VerifiedRealNameParam param){
			log.info("用户实名认证信息录入   请求参数：{}",EntityUtils.beanToMap(param));
			Map<String, Object> respMap = new HashMap<String, Object>();
			//String customerId = (String) param.get("customerId");
			// 信息类型 00：会员信息  01： 商户信息
			//String infoType = (String) param.get("infoType");
			Customer customer = customerMapper.selectByPrimaryKey(param.getCustomerId());
			if (null != customer) {
				if ("00".equals(param.getInfoType())) {
					if (null != customer.getPerId()) {
						//param.put("perId", customer.getPerId());
						param.setPerId(customer.getPerId());
						personalBaseBiz.verifiedRealName(param);
						
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					}else{
						respMap.put("code", ResponseCode.PER_NOTEXIST.getCode());
						respMap.put("msg", ResponseCode.PER_NOTEXIST.getMessage());
					}
				} else {
					if (null != customer.getMerId()) {
						// TODO 商户信息保存
						merchantBaseBiz.verifiedMerchant(param);
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					}else{
						respMap.put("code", ResponseCode.MER_NOTEXIST.getCode());
						respMap.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
					}
				}
				
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("用户实名认证信息录入   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 用户安全信息查询
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午2:00:35
		 * @param param
		 * @return
		 */
		public Map<String, Object> getSecurityInfo(String customerId){
			log.info("用户安全信息查询   请求参数：{}",customerId);
			Map<String, Object> respMap = new HashMap<String, Object>();
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			log.info("用户信息。。{}"+customer);
			if (null != customer) {
				if (!StringUtils.isEmpty(customer.getPerId())) {
					PersonalBase personalBase = personalBaseMapper.selectByPrimaryKey(customer.getPerId());
					respMap.put("custVerifyFlag", personalBase.getVerifyFlag());
					respMap.put("realName", personalBase.getRealName());
					//获取猎手是否绑定银行卡
					PersonalBindCard personalBindCard = new PersonalBindCard();
					personalBindCard.setPerId(customer.getPerId());
					personalBindCard.setStatus("00");
					List<PersonalBindCard> custBindCards = personalBindCardMapper.select(personalBindCard);
					if(null!=custBindCards&&custBindCards.size()>0){
						respMap.put("bindCard", "01");
					}else{
						respMap.put("bindCard", "00");
					}
				}else{
					respMap.put("custVerifyFlag", "00");
				}
				if (!StringUtils.isEmpty(customer.getMerId())) {
					MerchantBase merchantBase = merchantBaseMapper.selectByPrimaryKey(customer.getMerId());
					respMap.put("merVerifyFlag", merchantBase.getVerifyFlag());
				}else{
					respMap.put("merVerifyFlag", "00");
				}
				
				respMap.put("mobile", customer.getMobile());
				respMap.put("password", customer.getPassword());
				if(StringUtils.isEmpty(customer.getPassword())){
					respMap.put("loginPWDStatus", "01");//未设置
				}else{
					respMap.put("loginPWDStatus", "00");//正常
				}
				respMap.put("payPWDStatus", customer.getPayPasswordStatus());
				respMap.put("pwdStatus", customer.getPasswordStatus());
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("用户安全信息查询   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 修改手机号
		 * 1、判断用户是否存在
		 * 2、判断用户原手机号是否正确
		 * 3、判断原手机号和原验证码正确性
		 * 4、判断新手机号和新验证码正确性
		 * 5、更换手机号
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午2:24:30
		 * @param param
		 * @return
		 */
		public Map<String, Object> modifyCustomerMobile(ModifyCustomerMobileParam param){
			log.info("修改手机号   请求参数：{}",EntityUtils.beanToMap(param));
			Map<String, Object> respMap = new HashMap<String, Object>();
			Customer customer = customerMapper.selectByPrimaryKey(param.getCustomerId());
			if (null != customer) {
				if (param.getOldMobile().equals(customer.getMobile())) {
					Map<String, Object> smsMap = new HashMap<String, Object>();
					smsMap.put("mobile", param.getOldMobile());
					smsMap.put("code", param.getOldSmsCode());
					Map<String, Object> smsMapResp = smsGateWayBiz.verificationCode(smsMap);
					// 判断原手机号和原验证码正确性
					if (ResponseCode.OK.getCode().equals(smsMapResp.get("code")) && (Boolean)smsMapResp.get("verifyStatus")) {
						smsMap.put("mobile", param.getNewMobile());
						smsMap.put("code", param.getNewSmsCode());
						smsMapResp = smsGateWayBiz.verificationCode(smsMap);
						// 判断新手机号和新验证码正确性
						if (ResponseCode.OK.getCode().equals(smsMapResp.get("code")) && (Boolean)smsMapResp.get("verifyStatus")) {
							Customer checkCustomer=customerMapper.queryUserinfoByMobile(param.getNewMobile(),param.getPlatformId());
							if (null == checkCustomer) {
								customer.setMobile(param.getNewMobile());
								customer.setUpdatetime(new Timestamp(System.currentTimeMillis()));
								customerMapper.updateByPrimaryKey(customer);
								
								respMap.put("code", ResponseCode.OK.getCode());
								respMap.put("msg", ResponseCode.OK.getMessage());
							}else{
								respMap.put("code", ResponseCode.MOBILE_REPEAT.getCode());
								respMap.put("msg", ResponseCode.MOBILE_REPEAT.getMessage());
							}
							
						} else {
							respMap.put("code", ResponseCode.SMS_CODE_MATCH_FAIL.getCode());
							respMap.put("msg", ResponseCode.SMS_CODE_MATCH_FAIL.getMessage());
						}
					} else {
						respMap.put("code", ResponseCode.SMS_CODE_MATCH_FAIL.getCode());
						respMap.put("msg", ResponseCode.SMS_CODE_MATCH_FAIL.getMessage());
					}
					
				} else {
					respMap.put("code", ResponseCode.MOBILE_MATCH_FAIL.getCode());
					respMap.put("msg", ResponseCode.MOBILE_MATCH_FAIL.getMessage());
				}
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("修改手机号   响应参数：{}",respMap);
			return respMap;
		}
		
		
		//根据手机号获取登录用户信息,并校验用户密码是否正确,并返回上次登录角色、注册用户id、完善个人信息id和商户信息id
		//loginType//登录方式 00:表示手机号+密码登录；01:表示手机号+动态短信验证码登录
		public Map<String, Object> queryCustomerinfoByMobile(Map<String, Object> param){
			Map<String, Object> respMap = new HashMap<String, Object>();
			String mobile=(String)param.get("username");
			String passeword=(String)param.get("password");
			String platformId=(String)param.get("platformId");
			String simCode=(String)param.get("simCode");
			String loginType=(String)param.get("loginType");
			if("01".equals(loginType)){//短息验证码登录
			    if(!simCode.equals(redisTemplate.opsForValue().get("SMS_CODE_KEY:" + mobile))){
			    	respMap.put("code", ResponseCode.SMS_CODE_MATCH_FAIL.getCode());
					respMap.put("msg", ResponseCode.SMS_CODE_MATCH_FAIL.getMessage());
					return respMap;
			    }
			}
			try {
				Customer customer=customerMapper.queryUserinfoByMobile(mobile,platformId);
				if(null!=customer){
					if("00".equals(loginType)){//密码登录
						String inputpassword=MD5.sign(passeword, customer.getSaltvalue(), "utf-8");
						if(!customer.getPassword().equals(inputpassword)){
							respMap.put("code", ResponseCode.USERINFO_PWD_ERROR.getCode());
							respMap.put("msg", ResponseCode.USERINFO_PWD_ERROR.getMessage());
							return respMap;
						}
					}
					Customer newcustomer = new Customer();
					PersonalBase personalBase=new PersonalBase();
					MerchantBase merchantBase=new MerchantBase();
					newcustomer.setCustomerId(customer.getCustomerId());
					newcustomer.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
					customerMapper.updateByPrimaryKeySelective(newcustomer);
					respMap.put("lastLoginRole",customer.getLastLoginRole());//返回上次登录用户的角色
					respMap.put("customerId", customer.getCustomerId());//个人信息id
					//新增实名认证状态：个人实名认证和商户实名认证
					if(!StringUtils.isEmpty(customer.getPerId())){
						personalBase=personalBaseMapper.selectByPrimaryKey(customer.getPerId());
						if(null!=personalBase){
							respMap.put("perVerifyFlag", personalBase.getVerifyFlag());//个人信息id
						}else{
							respMap.put("perVerifyFlag", "");//个人信息id
						}
					}
					if(!StringUtils.isEmpty(customer.getMerId())){
						merchantBase=merchantBaseMapper.selectByPrimaryKey(customer.getMerId());
						if(null!=personalBase){
							respMap.put("merVerifyFlag", merchantBase.getVerifyFlag());//个人信息id
						}else{
							respMap.put("merVerifyFlag", "");//个人信息id
						}
					}
					respMap.put("perId", customer.getPerId());//个人信息id
					respMap.put("merId", customer.getMerId());//商户信息id
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				}else{
					respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
					respMap.put("msg", ResponseCode.USERINFO_NOTEXIST.getMessage());
				}
			} catch (Exception e) {
				respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.USERINFO_NOTEXIST.getMessage());
				e.printStackTrace();
				log.info("根据手机号获取登录用户信息报错：",e.getMessage());
			}
			return respMap;
		}
		
		/**
		 * 查询用户消息列表
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午4:53:21
		 * @param param
		 * @return
		 */
		public Map<String, Object> getCustomerMessage(Map<String, Object> param){
			log.info("查询用户消息列表   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = (String) param.get("customerId");
			int page = (int) param.get("page");
			int limit = (int) param.get("limit");
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("page", page);
			    params.put("limit", limit);
			    Query query = new Query(params);
			    Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
				List<CustomerMessage> userMessages = messageInfoMapper.queryCustomerMessage(param);
				TableResultResponse<CustomerMessage> table = new TableResultResponse<CustomerMessage>(result.getTotal(), userMessages);
				respMap.put("body", table);
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("查询用户消息列表   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 修改用户消息状态
		 * @author centerroot
		 * @time 创建时间:2018年5月23日下午5:06:04
		 * @param param
		 * @return
		 */
		public Map<String, Object> updateCustomerMessage(Map<String, Object> param){
			log.info("修改用户消息状态   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = (String) param.get("customerId");
			// type 00:已读操作  01：删除操作
			String type = (String) param.get("type");
			String msgIds = (String) param.get("msgIds");
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				String[] msgNoArr = msgIds.split(",");
				CustomerMessageRel messageRelReq = new CustomerMessageRel();
				messageRelReq.setCustomerId(customerId);
				for (int i = 0; i < msgNoArr.length; i++) {
					messageRelReq.setMsgId(msgNoArr[i]);
					CustomerMessageRel messageRelResp = customerMessageRelMapper.selectOne(messageRelReq);
					if (null != messageRelResp) {
						if ("00".equals(type)) {
							messageRelResp.setIsread("01");
						} else {
							messageRelResp.setIsdelete("01");
						}
						messageRelResp.setUpdatetime(new Timestamp(System.currentTimeMillis()));
						customerMessageRelMapper.updateByPrimaryKey(messageRelResp);
						log.info("更新用户消息关联关系操作：{}",messageRelResp.toString());
					} else {
						String seqNo = String.valueOf(SnowFlake.getId());
						messageRelReq.setSeqNo(seqNo);
						if ("00".equals(type)) {
							messageRelReq.setIsread("01");
						} else {
							messageRelReq.setIsdelete("01");
						}
						messageRelReq.setCreatetime(new Timestamp(System.currentTimeMillis()));
						customerMessageRelMapper.insert(messageRelReq);
						log.info("插入用户消息关联关系操作：{}",messageRelReq.toString());
					}
				}
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("修改用户消息状态   响应参数：{}",respMap);
			return respMap;
		}

		/**
		 * 查询用户最后收入记录
		 * @author centerroot
		 * @time 创建时间:2018年5月24日上午9:21:45
		 * @param param
		 * @return
		 */
		public Map<String, Object> getLastIncomeRecord(Map<String, Object> param){
			log.info("查询用户最后收入记录   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = (String) param.get("customerId");
			String platformId = (String) param.get("platformId");
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				if (null != customer.getPerId()) {
					Map<String, Object> reqBalMap = new HashMap<String, Object>();
					reqBalMap.put("perId", customer.getPerId());
					reqBalMap.put("platformId", platformId);
					reqBalMap.put("accType", AccountType.ACC_BALANCE.getCode());
					Map<String, Object> openAccMap = personalAccountBiz.openAccount(reqBalMap);
					PersonalAccount respPersonalAccount = (PersonalAccount) openAccMap.get("personalAccount");
					
					Map<String, Object> reqMap = new HashMap<String, Object>();
					reqMap.put("perId", customer.getPerId());
					reqMap.put("inOutFlag", "1");
					reqMap.put("accType", AccountType.ACC_BALANCE.getCode());
					reqMap.put("limitNum", 5);
					List<PersonalAccountJournalInfo> personalAccountJournals = personalAccountJournalMapper.queryTransactionRecord(reqMap);
					
					respMap.put("accBalance", respPersonalAccount.getAccBalance());
					respMap.put("personalAccountJournals", personalAccountJournals);
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
					
				} else {
					respMap.put("code", ResponseCode.PER_NOTEXIST.getCode());
					respMap.put("msg", ResponseCode.PER_NOTEXIST.getMessage());
				}
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("查询用户最后收入记录   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 查询用户交易记录
		 * @author centerroot
		 * @time 创建时间:2018年5月24日上午9:21:45
		 * @param param
		 * @return
		 */
		public Map<String, Object> queryPersonaTransactionRecord(Map<String, Object> param){
			log.info("查询用户交易记录   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = (String) param.get("customerId");
			String inOutFlag = (String) param.get("inOutFlag");
			int page = (int) param.get("page");
			int limit = (int) param.get("limit");
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				if (null != customer.getPerId()) {
					PersonalAccount reqPersonalAccount = new PersonalAccount();
					reqPersonalAccount.setPerId(customer.getPerId());
					reqPersonalAccount.setAccType(AccountType.ACC_BALANCE.getCode());
					PersonalAccount respPersonalAccount = personalAccountBiz.selectOne(reqPersonalAccount);
					if (null != respPersonalAccount) {
						param.put("perId", customer.getPerId());
						param.put("accType", AccountType.ACC_BALANCE.getCode());
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("page", page);
						params.put("limit", limit);
						Query query = new Query(params);
						Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
						List<PersonalAccountJournalInfo> personalAccountJournals = personalAccountJournalMapper.queryTransactionRecord(param);
						TableResultResponse<PersonalAccountJournalInfo> table = new TableResultResponse<PersonalAccountJournalInfo>(result.getTotal(), personalAccountJournals);
						respMap.put("body", table);
						respMap.put("accBalance", respPersonalAccount.getAccBalance());
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					} else {
						respMap.put("code", ResponseCode.PER_ACC_NOTEXIST.getCode());
						respMap.put("msg", ResponseCode.PER_ACC_NOTEXIST.getMessage());
					}
				} else {
					respMap.put("code", ResponseCode.PER_NOTEXIST.getCode());
					respMap.put("msg", ResponseCode.PER_NOTEXIST.getMessage());
				}
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("查询用交易记录   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 查询商户交易记录
		 * @author centerroot
		 * @time 创建时间:2018年5月28日下午1:51:20
		 * @param param
		 * @return
		 */
		public Map<String, Object> queryMerchantTransactionRecord(Map<String, Object> param){
			log.info("查询商户交易记录   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId = (String) param.get("customerId");
			Customer customer = customerMapper.selectByPrimaryKey(customerId);
			if (null != customer) {
				if (null != customer.getMerId()) {
					MerchantAccount reqMerchantAccount = new MerchantAccount();
					reqMerchantAccount.setMerId(customer.getMerId());
					reqMerchantAccount.setAccType(AccountType.ACC_BALANCE.getCode());
					MerchantAccount respMerchantAccount = merchantAccountBiz.selectOne(reqMerchantAccount);
					
					
					MerchantAccount reqMerAccountFreeze = new MerchantAccount();
					reqMerAccountFreeze.setMerId(customer.getMerId());
					reqMerAccountFreeze.setAccType(AccountType.ACC_BALANCE.getCode());
					MerchantAccount respMerAccountFreeze = merchantAccountBiz.selectOne(reqMerAccountFreeze);
					if (null != respMerchantAccount) {
						param.put("perId", customer.getPerId());
						param.put("accType", AccountType.ACC_BALANCE.getCode());
						List<MerchantAccountJournalInfo> merchantAccountJournalInfos = merchantAccountJournalMapper.queryTransactionRecord(param);
						
						
						if (null != respMerAccountFreeze) {
							respMap.put("accFreezeBalance", respMerAccountFreeze.getAccBalance());
						}
						respMap.put("accBalance", respMerchantAccount.getAccBalance());
						respMap.put("merchantAccountJournalInfos", merchantAccountJournalInfos);
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					} else {
						respMap.put("code", ResponseCode.MER_ACC_NOTEXIST.getCode());
						respMap.put("msg", ResponseCode.MER_ACC_NOTEXIST.getMessage());
					}
				} else {
					respMap.put("code", ResponseCode.MER_NOTEXIST.getCode());
					respMap.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
				}
			}else{
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
			}
			log.info("查询商户交易记录   响应参数：{}",respMap);
			return respMap;
		}
		
		/**
		 * 查询会员列表
		 * @author chj
		 * @param param
		 * @return
		 */
		public TableResultResponse<Map<String, Object>> queryMemberList(Map<String, Object> param) {
			log.info("查询会员列表参数。。。{}"+param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			Map<String, Object> params = new HashMap<String, Object>();
	        Integer page = (Integer) param.get("page");
	        Integer limit = (Integer) param.get("limit");
			params.put("page", page);
			params.put("limit", limit);
			Query query = new Query(params);
			Page<Object> result = null;
			List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
			if ("001".equals(param.get("type"))) {
				result = PageHelper.startPage(query.getPage(), query.getLimit());
				res = customerMapper.queryPersonalMemberList(param);
				log.info("查询会员列表。。。{}"+res);
			}else if ("002".equals(param.get("type"))) {
				result = PageHelper.startPage(query.getPage(), query.getLimit());
				res = customerMapper.queryMerchantMemberList(param);
				log.info("查询商户列表。。。{}"+res);
			}
			TableResultResponse<Map<String, Object>> response = new TableResultResponse<Map<String, Object>>(result.getTotal(), res);
			return response;
		}
		
		/**
		 * 查询会员信息
		 * @author chj
		 * @param param
		 * @return
		 */
		public Map<String, Object> queryMemberInfo(Map<String, Object> param) {
			log.info("查询会员信息参数。。。{}"+param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			Map<String, Object> res = customerMapper.queryMemberInfo(param);
			String perId = (String) res.get("perId");
			if (!StringUtils.isEmpty(perId)) {
				//个人绑定银行卡
				Map<String, Object> req = new HashMap<>();
				req.put("perId", perId);
				List<PersonalBindCard> list = bindCardMapper.queryPersonalBindCardMap(req);
				log.info("银行卡列表。。。{}"+list);
				respMap.put("bankCards", list);
			}
			respMap.put("memberInfo", res);
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
			log.info("查询会员信息。。。{}"+respMap);
			return respMap;
		}
		
		/**
		 * 修改会员信息
		 * @author chj
		 * @param param
		 * @return
		 */
		public Map<String, Object> updateAccountStatus(Map<String, Object> param) {
			log.info("修改会员状态参数。。。{}"+param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			customerMapper.updateAccountStatus(param);
			log.info("修改会员状态完成。。。{}");
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
			return respMap;
		}
		
		/**
		 * 用户注册
		 * @param 
		 * 
		 * 
		 * */
		public Map<String, Object> userRegister(Map<String, Object> param){
			log.info("用户信息注册   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String mobile=(String) param.get("mobile");
			String loginRole=(String) param.get("loginRole");//登录权限
			String simcode=(String) param.get("simCode");//短信验证码
			String platformId=(String) param.get("platformId");
			if(!simcode.equals(redisTemplate.opsForValue().get("SMS_CODE_KEY:" + mobile))){
				respMap.put("code", ResponseCode.SMS_CODE_MATCH_FAIL.getCode());
				respMap.put("msg", ResponseCode.SMS_CODE_MATCH_FAIL.getMessage());
				return respMap;
			}
			Customer registerUser=customerMapper.queryUserinfoByMobile(mobile,platformId);
			if(null!=registerUser){
				respMap.put("code", ResponseCode.USERINFO_ISEXIST.getCode());
				respMap.put("msg", ResponseCode.USERINFO_ISEXIST.getMessage());
				return respMap;
			}
			Customer customer= new Customer();
			String customerId =String.valueOf(SnowFlake.getId());
			//获取用户随机盐值
			String saltvalue=MD5.generateSaltkey();
			String password=MD5.sign((String) param.get("password"),saltvalue, "utf-8");
			try {
				String perId="";
				String merId="";
				if(LoginRole.personal.getCode().equals(loginRole)){//个人登录
					perId= String.valueOf(SnowFlake.getId());
				}else if(LoginRole.merchant.getCode().equals(loginRole)){//商户登录
					merId= String.valueOf(SnowFlake.getId());
				}
				customer.setCustomerId(customerId);
				customer.setPlatformId(platformId);
				customer.setMobile(mobile);
				customer.setPassword(password);
				customer.setPasswordStatus("00");//密码状态 00：正常，01：锁定
				customer.setPayPasswordStatus("01");//支付密码状态 未设置
				customer.setCustomerType("01");//用户类型  00:平台（渠道）  01：普通客户
				customer.setPerId(perId);
				customer.setPayPasswordStatus("01");
				customer.setMerId(merId);
				customer.setSaltvalue(saltvalue);
				customer.setAccountStatus("00");//账户状态 00：正常，01：客户冻结
				customer.setLastLoginRole(loginRole);
				customer.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
				customer.setCreatetime(new Timestamp(System.currentTimeMillis()));
				int isInsertOK=customerMapper.insertSelective(customer);
				if(isInsertOK>0){
					//添加个人基础信息 
					if(!StringUtils.isEmpty(perId)){
						PersonalBase personalBase=new PersonalBase();
						//生成个人会员号
						String perNo = String.valueOf(SnowFlake.getId());
						//String perNo = CRC16M.getCRCNo(customerIdStr);
						personalBase.setPerId(perId);
						personalBase.setPerNo(perNo);
						personalBase.setCustomerId(customerId);
						personalBase.setVerifyFlag("00");//实名状态  00：未实名  01：已实名  02：待审核
						personalBase.setCreatetime(new Timestamp(System.currentTimeMillis()));
						personalBase.setUpdatetime(new Timestamp(System.currentTimeMillis()));
						personalBaseMapper.insertSelective(personalBase);
					}
					//添加商户基础信息
					if(!StringUtils.isEmpty(merId)){
						MerchantBase merchantBase =new MerchantBase();
						//生成商户会员号
						String merchantNo = String.valueOf(SnowFlake.getId());
						//String merchantNo = CRC16M.getCRCNo(customerIdStr);
						merchantBase.setMerId(merId);
						merchantBase.setMerchantNo(merchantNo);
						merchantBase.setCustomerId(customerId);
						merchantBase.setVerifyFlag("00");//实名状态  00：未实名  01：已实名  02：待审核
						merchantBase.setCreatetime(new Timestamp(System.currentTimeMillis()));
						merchantBase.setUpdatetime(new Timestamp(System.currentTimeMillis()));
						merchantBaseMapper.insertSelective(merchantBase);
					}
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				}else{
					respMap.put("code", ResponseCode.REGISTER_ERROR.getCode());
					respMap.put("msg", ResponseCode.REGISTER_ERROR.getMessage());
				}
				
			} catch (Exception e) {
				log.info("用户注册异常---",e.getMessage());
				e.printStackTrace();
				respMap.put("code", ResponseCode.REGISTER_ERROR.getCode());
				respMap.put("msg", ResponseCode.REGISTER_ERROR.getMessage());
				return respMap;
			}
			return respMap;
		}
		
		/**
		 * 平台开通商户账户
		 * @author centerroot
		 * @time 创建时间:2018年5月31日下午5:44:24
		 * @param param
		 * @return
		 */
		public Map<String, Object> planformOpenAccount(Map<String, Object> param) {
			log.info("平台开通商户账户。。。{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String platformId = (String) param.get("platformId");
			String custName = (String) param.get("custName");
			String businessNo = (String) param.get("businessNo");
			String legalPersonName = (String) param.get("legalPersonName");
			String legalPersonCredType = (String) param.get("legalPersonCredType");
			String legalPersonCredNo = (String) param.get("legalPersonCredNo");
			String businessScope = (String) param.get("businessScope");
			String businessLicence = (String) param.get("businessLicence");
			String address = (String) param.get("address");
			String httpAddress = (String) param.get("httpAddress");
			BigDecimal registerAmount = (BigDecimal) param.get("registerAmount");
			String telephone = (String) param.get("telephone");
			
			Customer customer = new Customer();
			String customerId = String.valueOf(SnowFlake.getId());
			String merId = String.valueOf(SnowFlake.getId());
			String merchantNo = String.valueOf(SnowFlake.getId());
			customer.setCustomerId(customerId);
			customer.setPlatformId(platformId);
			customer.setCustomerType("00");
			customer.setMerId(merId);
			customer.setAccountStatus("00");
			customer.setCreatetime(new Timestamp(System.currentTimeMillis()));
			customerMapper.insert(customer);
			MerchantBase merchantBase = new MerchantBase();
			merchantBase.setMerId(merId);
			merchantBase.setCustomerId(customerId);
			merchantBase.setMerchantNo(merchantNo);
			merchantBase.setMerType("00");
			merchantBase.setCustName(custName);
			merchantBase.setBusinessNo(businessNo);
			merchantBase.setLegalPersonName(legalPersonName);
			merchantBase.setLegalPersonCredType(legalPersonCredType);
			merchantBase.setLegalPersonCredNo(legalPersonCredNo);
			merchantBase.setBusinessScope(businessScope);
			merchantBase.setBusinessLicence(businessLicence);
			merchantBase.setAddress(address);
			merchantBase.setHttpAddress(httpAddress);
			merchantBase.setRegisterAmount(registerAmount);
			merchantBase.setTelephone(telephone);
			merchantBase.setVerifyFlag("01");
			merchantBase.setAccountStatus("00");
			merchantBase.setCreatetime(new Timestamp(System.currentTimeMillis()));
			merchantBaseMapper.insert(merchantBase);
			
			
			
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
			log.info("平台开通商户账户。。。{}",respMap);
			return respMap;
		}
		/**
		 *申请成为猎手或者悬赏方 
		 * */
		public Map<String, Object> applyRole(Map<String, Object> param){
			log.info("申请成为猎手或者悬赏方 。。。{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId=(String) param.get("customerId");
			String operType=(String) param.get("operType");//登录权限
			Customer record=customerMapper.selectByPrimaryKey(customerId);
			if(null==record){//用户不存在
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
				return respMap;
			}
			try {
				if("01".equals(operType)){//表示申请成为猎手
					PersonalBase personalBase=new PersonalBase();
					//生成个人会员号
					String perNo = String.valueOf(SnowFlake.getId());
					String perId= String.valueOf(SnowFlake.getId());
					//String perNo = CRC16M.getCRCNo(customerIdStr);
					personalBase.setPerId(perId);
					personalBase.setPerNo(perNo);
					personalBase.setCustomerId(customerId);
					personalBase.setVerifyFlag("00");//实名状态  00：未实名  01：已实名  02：待审核
					personalBase.setCreatetime(new Timestamp(System.currentTimeMillis()));
					personalBase.setUpdatetime(new Timestamp(System.currentTimeMillis()));
					personalBaseMapper.insertSelective(personalBase);
					Customer nercust=new Customer();
					nercust.setCustomerId(customerId);
					nercust.setPerId(perId);
					customerMapper.updateByPrimaryKeySelective(nercust);
					respMap.put("perId", perId);
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				}
				if("02".equals(operType)){//表示申请成为悬赏方
					MerchantBase merchantBase =new MerchantBase();
					//生成商户会员号
					String merchantNo = String.valueOf(SnowFlake.getId());
					String merId= String.valueOf(SnowFlake.getId());
					//String merchantNo = CRC16M.getCRCNo(customerIdStr);
					merchantBase.setMerId(merId);
					merchantBase.setMerchantNo(merchantNo);
					merchantBase.setCustomerId(customerId);
					merchantBase.setVerifyFlag("00");//实名状态  00：未实名  01：已实名  02：待审核
					merchantBase.setCreatetime(new Timestamp(System.currentTimeMillis()));
					merchantBase.setUpdatetime(new Timestamp(System.currentTimeMillis()));
					merchantBaseMapper.insertSelective(merchantBase);
					Customer nercust=new Customer();
					nercust.setCustomerId(customerId);
					nercust.setMerId(merId);
					customerMapper.updateByPrimaryKeySelective(nercust);
					respMap.put("merId", merId);
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				}
			} catch (Exception e) {
				log.info("申请成为猎手或者悬赏方异常---",e.getMessage());
				e.printStackTrace();
				respMap.put("code", ResponseCode.APPLYROLE_FAIL.getCode());
				respMap.put("msg", ResponseCode.APPLYROLE_FAIL.getMessage());
			}
			return respMap;
		}
		
		/**
		 *切换用户登录角色
		 * */
		public Map<String, Object> changeRole(Map<String, Object> param){
			log.info("切换用户登录角色 。。。{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId=(String) param.get("customerId");
			String lastLoginRole=(String) param.get("lastLoginRole");//最后登录角色
			Customer record=customerMapper.selectByPrimaryKey(customerId);
			if(null==record){//用户不存在
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
				return respMap;
			}
			try {
				record.setLastLoginRole(lastLoginRole);
				customerMapper.updateByPrimaryKeySelective(record);
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				log.info("申请成为猎手或者悬赏方异常---",e.getMessage());
				respMap.put("code", ResponseCode.CHANGEROLE_FAIL.getCode());
				respMap.put("msg", ResponseCode.CHANGEROLE_FAIL.getMessage());
			}
			return respMap;
		}
		/**
		 * 用户退出登录
		 * */
		public Map<String, Object> userLoginout(Map<String, Object> param){
			log.info("用户退出登录 。。。{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String customerId=(String) param.get("customerId");
			Customer record=customerMapper.selectByPrimaryKey(customerId);
			if(null==record){//用户不存在
				respMap.put("code", ResponseCode.CUST_NOTEXIST.getCode());
				respMap.put("msg", ResponseCode.CUST_NOTEXIST.getMessage());
				return respMap;
			}
			try {
				redisTemplate.delete("login:token_"+record.getMobile());
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				log.info("用户退出登录异常---",e.getMessage());
				respMap.put("code", ResponseCode.USERLOGINOUT_FAIL.getCode());
				respMap.put("msg", ResponseCode.USERLOGINOUT_FAIL.getMessage());
			}
			return respMap;
		}
		
		/**
		 * 查询用户基础信息
		 * @author centerroot
		 * @time 创建时间:2018年6月22日下午3:02:21
		 * @param param
		 * @return
		 */
		public Map<String, Object> queryCustomerInfo(Map<String, Object> param){
			log.info("获取用户统计数据   请求参数：{}",param);
			Map<String, Object> respMap = new HashMap<String, Object>();
			String platformId = (String) param.get("platformId");
			String customerId = (String) param.get("customerId");
			String customerType = (String) param.get("customerType");
			String merId = (String) param.get("merId");
			String perId = (String) param.get("perId");
			String mobile = (String) param.get("mobile");
			
			Customer customerReq = new Customer();
			customerReq.setPlatformId(platformId);
			customerReq.setCustomerId(customerId);
			customerReq.setCustomerType(customerType);
			customerReq.setMerId(merId);
			customerReq.setPerId(perId);
			customerReq.setMobile(mobile);
			Customer customerResp = customerMapper.selectOne(customerReq);
			if (null != customerResp) {
				respMap.put("customer", EntityUtils.beanToMap(customerResp));
			}
			if (null != customerResp && null != customerResp.getMerId()) {
				MerchantBase merchantBase = merchantBaseBiz.selectById(customerResp.getMerId());
				if (null != merchantBase) {
					respMap.put("merchantBase", EntityUtils.beanToMap(merchantBase));
				}
			}
			if (null != customerResp && null != customerResp.getPerId()) {
				PersonalBase personalBase = personalBaseBiz.selectById(customerResp.getPerId());
				if (null != personalBase) {
					respMap.put("personalBase", EntityUtils.beanToMap(personalBase));
				}
			}
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
			
			log.info("获取用户统计数据   响应参数：{}",respMap);
			return respMap;
		}

}